package com.wyt.common.file.video.h264Tortmp;


import org.java_websocket.client.WebSocketClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 辅助控制类
 */
@RestController
@RequestMapping("/assist")
public class H264TRtmp {
    private static Logger logger = LoggerFactory.getLogger(H264TRtmp.class);

    private Map<String, H264PushRtmp> deviceIdRtmp = new HashMap<>();
    @PostMapping("/openOrCloseH264ToRtmp")
    public String openOrCloseH264ToRtmp(@RequestBody H264ToRtmpReq request){
        switch (request.getType()){
            case "open":
                if (deviceIdRtmp.containsKey(request.getDeviceId()))return "该装备正在推rtmp，请勿重复推流！";
                H264PushRtmp pushRtmp = new H264PushRtmp(request.getDeviceId(), request.getRtmpUrl(), request.getWsUrl());
                new Thread(pushRtmp).start();
                try {
                    //启动websocket监听视频流,将接收到的字节通过管道传输到推送线程中
                    WebSocketClient wsClient = pushRtmp.getWsClient();
                    while (!wsClient.isOpen()) {
                        System.out.println(1);
                        Thread.sleep(1000);
                    }
                    logger.info("{}链接成功.....",request.getWsUrl());
                    deviceIdRtmp.put(request.getDeviceId(),pushRtmp);
                } catch (Exception e) {
                    logger.info("{} websocket获取视频流失败，",request.getWsUrl(),e);
                    pushRtmp.stopPush();
                }
                break;
            case "close":
                H264PushRtmp remove = deviceIdRtmp.remove(request.getDeviceId());
                if (remove!=null) remove.stopPush();
                break;
            default:
                return "类型参数只能填open或close，不支持"+request.getType();
        }
        return "装备"+request.getDeviceId()+" " +request.getType()+"成功";
    }

}
